from pylab import *
from numpy import *


a=imread("gray1.png")[:,:,0]
b=imread("gray2.png")[:,:,0]
c=imread("gray3.png")[:,:,0]
d=imread("gray4.png")[:,:,0]
e=imread("gray5.png")[:,:,0]
f=imread("gray6.png")[:,:,0]
g=imread("gray7.png")[:,:,0]
h=imread("gray8.png")[:,:,0]


t1=a.shape[0]
t2=a.shape[1]

a1=a.ravel()
b1=b.ravel()
c1=c.ravel()
d1=d.ravel()
e1=e.ravel()
f1=f.ravel()
g1=g.ravel()
h1=h.ravel()

x,y=mgrid[0:t2,0:t1]

x2=x.ravel()
y2=y.ravel()

lg={}

j=[]

for k in range(len(a1)):
	lc=[]
	lc.append(a1[k])
	lc.append(b1[k])
	lc.append(c1[k])
	lc.append(d1[k])
	lc.append(e1[k])
	lc.append(f1[k])
	lc.append(g1[k])
	lc.append(h1[k])
	lg[(x2[k],y2[k])] = lc	
    
       


#############################################################################
def Graytodec(g):

    
#Convierte un numero en codigo Gray a decimal. La entrada debe ser una lista de 8 elementos 
    
    b=[g[0]]

    for i in range(1,8):
    
        if g[i]==0:
            b.append(b[i-1])
        if g[i]==1:
            if b[i-1]==0:
                b.append(1)
            if b[i-1]==1:
                b.append(0)


    n8=b[0]*(2**7)
    n7=b[1]*(2**6)
    n6=b[2]*(2**5)
    n5=b[3]*(2**4)
    n4=b[4]*(2**3)
    n3=b[5]*(2**2)
    n2=b[6]*(2**1)
    n1=b[7]*(2**0)

    num=n1+n2+n3+n4+n5+n6+n7+n8
    
    
    return num
######################################################################



#~ 
#w=[]
#w=lg.values().copy()
#~ 
#~ l=[]
#~ 
#~ for s in lg.values():
    #~ l.append(Graytodec(s))

k=0
for key in lg.keys():
	if k%100000==0:print k
	aux = Graytodec(lg[key])
	lg[key]=aux
	k+=1

 #   b=[]		
mat0=zeros((t2,t1))
#~ 
v=0
for k in range(len(lg)):
      x=lg.keys()[k][0]
      y=lg.keys()[k][1]
      if v%100==0:print v
      mat0[(x,y)]=lg[(x,y)]#array(lg.values()[k])	
      v=v+1	#~ 
  
#print (lg)

#print lg(1,1)
#~ print w
#~ print len(w)
#~ print len(lg)
#~ print a.shape[0]*a.shape[1]
